package com.algorithm;

import java.util.ArrayList;
import java.util.List;

/**
 * 螺旋矩阵
 */
public class SpiralMatrix {

    public static List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> list=new ArrayList<Integer>();
        int left = 0;
        int right = matrix[0].length-1;
        int top = 0;
        int bottom = matrix.length-1;
        int direct = 1;
        while (left <= right && top <= bottom) {
            if (direct == 1) {
                for (int i=left;i<=right;i++){
                    list.add(matrix[top][i]);
                }
                top++;
                direct = 2;
            } else if (direct == 2) {
                for (int i=top;i<=bottom;i++){
                    list.add(matrix[i][right]);
                }
                direct = 3;
                right--;
            }else if(direct == 3){
                for (int i=right;i>=left;i--){
                    list.add(matrix[bottom][i]);
                }
                bottom--;
                direct = 4;
            }else {
                for (int i=bottom;i>=top;i--){
                    list.add(matrix[i][left]);
                }
                left++;
                direct = 1;
            }
        }
        return list;
    }

    public static void main(String[] args) {
//        int[][] matrix = new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
        int[][] matrix = new int[][]{{1,2,3,4},{5,6,7,8},{9,10,11,12}};
        List<Integer> list = spiralOrder(matrix);
        System.out.println(list);
    }
}
